package net.nlimi.tel;

import java.util.Calendar;

import java.util.Timer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.nlimi.tel.HttpConnection.CallbackListener;
import net.nlimi.tel.mo.MoNPhone;
import android.app.Activity;
import android.text.InputType;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;

public class TelActivity extends Activity{
	private EditText showInput;
	private ListAdapter adapter;
	private ListView NTListView;
	private LinearLayout searchResult;
	private TextView searchLocalResult;
	private TextView searchWebResult;
	
	private BaseDbListData dataContacts;
	private BaseDbListData dataPhone;
	private BaseDbListData dataHttp;
	
	//private final Timer timer = new Timer();

	private int sdMinHeight = 80;
	private int sdMaxHeight = 420;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Log.d("CD", "start");
		
		//new ZContactsSynchroService().init(this);
        //*
        Intent ListenService = new Intent( this, ZContactsListenService.class );
        stopService(ListenService);
        ListenService.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
        startService(ListenService);
        Log.d("CD", "start1");
       
		DisplayMetrics dm = new DisplayMetrics();  
		getWindowManager().getDefaultDisplay().getMetrics(dm);  
		int height = dm.heightPixels;  
		if (800<=height && height<1280){
			sdMinHeight = 80;
			sdMaxHeight=440;
		}else if(1280<=height){
			sdMinHeight = 100;
			sdMaxHeight=600;
		}
		RelativeLayout telNo = (RelativeLayout) findViewById(R.id.telNo);
		telNo.getLayoutParams().height=sdMinHeight;
		telNo.invalidate();
		//Log.d("CD", "height:"+height);
		
        //设置显示标记为本的号码
        searchResult = (LinearLayout) findViewById(R.id.searchResult);
        searchResult.setTag(R.string.show, "calllog");
        
        searchLocalResult = (TextView) findViewById(R.id.searchLocalResult);
        searchLocalResult.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ToggleResult(v, "local");
			}
		});
        
        searchWebResult = (TextView) findViewById(R.id.searchWebResult);
        searchWebResult.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ToggleResult(v, "http");
			}
		});
        
        dataContacts = new MoCallLog(this);
        dataHttp = new MoHttpAsynchro(callbackListener);
        dataHttp.setTip(searchWebResult);
		dataPhone = new MoNPhone(this);	        
        
		this.getWindow().setBackgroundDrawableResource(R.drawable.white);
		findViewById(R.id.telNoContent).setBackgroundResource(R.drawable.white);
		findViewById(R.id.showline).setBackgroundResource(R.drawable.white);
		
		//* 隐藏输入法
		EditText phoneno = (EditText) findViewById(R.id.phoneno);
		phoneno.setInputType(InputType.TYPE_NULL);
		
		EditText phoneno_c = (EditText) findViewById(R.id.phoneno_c);
		phoneno_c.setInputType(InputType.TYPE_NULL);
		phoneno_c.setTag("show");
		phoneno_c.setOnFocusChangeListener(new OnFocusChangeListener(){
			@Override
			public void onFocusChange(View v, boolean arg1) {
				ShowHideKeyboard(v);
			}
		});
		this.showInput = phoneno_c;
		
		//* 设置隐藏显示按钮
		Button showsd = (Button) findViewById(R.id.showsd);
		showsd.setTag("show");
		showsd.setOnClickListener(shsdOnClick);
		
		Button hidesd = (Button) findViewById(R.id.hidesd);
		hidesd.setTag("hide");
		hidesd.setOnClickListener(shsdOnClick);  
		
		//* 设置数字按钮
		Button btn1 = (Button) findViewById(R.id.button_1);
		btn1.setTag(1);
        btn1.setOnClickListener(bhlistener);
        
		Button btn2 = (Button) findViewById(R.id.button_2);
		btn2.setTag(2);
		btn2.setOnClickListener(bhlistener);
        
		Button btn3 = (Button) findViewById(R.id.button_3);
		btn3.setTag(3);
		btn3.setOnClickListener(bhlistener);
        
		Button btn4 = (Button) findViewById(R.id.button_4);
		btn4.setTag(4);
		btn4.setOnClickListener(bhlistener);
        
		Button btn5 = (Button) findViewById(R.id.button_5);
		btn5.setTag(5);
		btn5.setOnClickListener(bhlistener);
        
		Button btn6 = (Button) findViewById(R.id.button_6);
		btn6.setTag(6);
		btn6.setOnClickListener(bhlistener);
        
		Button btn7 = (Button) findViewById(R.id.button_7);
		btn7.setTag(7);
		btn7.setOnClickListener(bhlistener);
        
		Button btn8 = (Button) findViewById(R.id.button_8);
		btn8.setTag(8);
		btn8.setOnClickListener(bhlistener);
		
		Button btn9 = (Button) findViewById(R.id.button_9);
		btn9.setTag(9);
		btn9.setOnClickListener(bhlistener);
		
		Button btn0 = (Button) findViewById(R.id.button_0);
		btn0.setTag(0);
		btn0.setOnClickListener(bhlistener);
		
		Button btnend = (Button) findViewById(R.id.button_end);
		btnend.setTag("*");
		btnend.setOnClickListener(bhlistener);
		
		Button btnasterisk = (Button) findViewById(R.id.button_asterisk);
		btnasterisk.setTag("#");
		btnasterisk.setOnClickListener(bhlistener);

		// 删除按钮
        Button btn_del = (Button) findViewById(R.id.button_del);
        btn_del.setOnClickListener(new OnClickListener(){
        	public void onClick(View v) {
        		//final EditText et = (EditText) findViewById(R.id.phoneno);
        		  // TODO Auto-generated method stub
        		deleteText(showInput);
        	}
        });
        
        Button btn_del_c = (Button) findViewById(R.id.button_del_c);
        btn_del_c.setOnClickListener(new OnClickListener(){
        	public void onClick(View v) {
        		//final EditText et = (EditText) findViewById(R.id.phoneno_c);
        		  // TODO Auto-generated method stub
        		deleteText(showInput);
        	}
        });
        
		// 电话及短信
		Button btn_tel = (Button) findViewById(R.id.button_tel);
        btn_tel.setOnClickListener(callOnClick);
        
        Button btn_sms = (Button) findViewById(R.id.button_sms);
        btn_sms.setOnClickListener(smsOnClick);
        
        // 加载联系人列表
        //ArrayList<Map<String, Object>> mData = new Tel(this).getContacts();
        adapter = new ListAdapter(this, dataContacts, "calllog"); 
        adapter.setShowInput(phoneno_c);
        
        NTListView = (ListView) findViewById(R.id.PhoneView);
        NTListView.setAdapter(adapter);
        //adapter.setListView(NTListView);
        
        //*/
	}
  
	// 搜索号码
	public void findRqeuest(String keyword) {
		// 加载网络搜索结果
		Log.d("CD","findRqeuest");	
		dataPhone.search(keyword);
		dataHttp.search(keyword);
		//dataHttp  = new MoHttp(keyword);	
	
		String nowflag = (String) searchResult.getTag(R.string.show);
		// 无搜索关键字处理，隐藏显示数量框	
		if (keyword.length()<1){
			searchResult.setVisibility(8);
			//if (nowflag=="http"){				
			//	ToggleResult(searchResult, "local");
			//}
			dataContacts.refresh();
			searchWebResult.setBackgroundResource(R.drawable.gray);
			searchLocalResult.setBackgroundResource(R.drawable.white);	
			adapter.setDataAndMode(dataContacts, "calllog");
			searchResult.setTag(R.string.show, "calllog");
			NTListView.setAdapter(adapter);
		}else{
			searchResult.setVisibility(0);
			searchWebResult.setText("搜索中,请稍后...");
			searchLocalResult.setText(">> "+dataPhone.getCount()+"条本地结果 <<");			
			
			// 刷新号码列表
			nowflag = (nowflag=="local" || nowflag=="calllog") ? "local" : "http";
			adapter.setDataAndMode(nowflag=="local" ? dataPhone : dataHttp, nowflag);
			searchResult.setTag(R.string.show, nowflag);
			NTListView.setAdapter(adapter);
		}
		//adapter.notifyDataSetChanged();
	}
	private void ToggleResult(View v, String flag){
		String nowflag = (String) searchResult.getTag(R.string.show);
		if (nowflag==flag){ return ; }
		
		Log.d("CD","ToggleResult"+flag);
		if (flag=="http"){
			// 显示网络请求数据
			adapter.setDataAndMode(dataHttp, "http");
			NTListView.setAdapter(adapter);	
			searchResult.setTag(R.string.show, "http");
			
			searchWebResult.setBackgroundResource(R.drawable.white);
			searchLocalResult.setBackgroundResource(R.drawable.gray);
		}else{
			// 显示本地查询数据
			adapter.setDataAndMode(dataPhone, "local");
			NTListView.setAdapter(adapter);	
			searchResult.setTag(R.string.show, "local");
			
			searchWebResult.setBackgroundResource(R.drawable.gray);
			searchLocalResult.setBackgroundResource(R.drawable.white);		
		}
		//adapter.notifyDataSetChanged();
	}
	private CallbackListener callbackListener = new HttpConnection.CallbackListener() {  
        @Override  
        public void callBack(String result) {  
        	//al(result);
        	Log.d("CD","data:"+result);
        	if (result=="fail"){
        		searchWebResult.setText(">> 网络连接错误 <<");
        	}else{
	        	dataHttp.parseJson(result);
	        	searchWebResult.setText(">> "+dataHttp.getQueryCount()+"条网络结果 <<");
	        	
	        	String nowflag = (String) searchResult.getTag(R.string.show);
	        	if (nowflag=="http"){
		        	// 刷新号码列表
		        	adapter.setDataAndMode(dataHttp, nowflag);
		        	adapter.notifyDataSetChanged();
		        	//NTListView.setAdapter(adapter);
	        	}
        	}
        }  
    }; 
    private void al(String msg){
    	Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

	// 调用打电话
	private OnClickListener callOnClick = new OnClickListener(){
		public void onClick(View v) {
			final TextView show = (TextView) findViewById(R.id.phoneno);
			new Tel(v.getContext()).Call(v, show.getText().toString());
			/*Intent intent=new Intent
					(Intent.ACTION_CALL,Uri.parse("tel:"+show.getText()));
			startActivity(intent);*/
		}
	};
	// 调用发短信
	private OnClickListener smsOnClick = new OnClickListener(){
		public void onClick(View v) {
			final TextView show = (TextView) findViewById(R.id.phoneno);
			String iphone = show.getText().toString();
			new Tel(v.getContext()).Sms(v, iphone);
			/*
			Intent intent=new Intent();
			intent.setClass(TelActivity.this,Bh_smsActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("iphone", iphone);
			intent.putExtras(bundle);
			startActivity(intent);*/
		}
	};	
	// 隐藏虚拟号码框
	private OnClickListener shsdOnClick = new OnClickListener(){
		public void onClick(View v) {
			Log.e("CD", "swevice");
			ShowHideKeyboard(v);
		}
	};
	public void ShowHideKeyboard(View v){
		RelativeLayout telNo = (RelativeLayout) findViewById(R.id.telNo);
		
		SlidingDrawer sd = (SlidingDrawer) findViewById(R.id.drawer1);
		LinearLayout showline = (LinearLayout) findViewById(R.id.showline);
		final EditText phoneno = (EditText) findViewById(R.id.phoneno);
		final EditText phoneno_c = (EditText) findViewById(R.id.phoneno_c);
		
		if (v.getTag().equals("show")){			
			sd.animateOpen();
		}else{
			sd.animateClose();
		}
		// 设定虚拟键盘可见内容,及当前焦点输入框
		if (sd.isOpened()){
			telNo.getLayoutParams().height=sdMinHeight;
			showline.setVisibility(0);
			phoneno_c.setText(phoneno.getText());
			phoneno_c.setSelection(phoneno.getSelectionStart());
			adapter.setShowInput(phoneno_c);
			this.showInput = phoneno_c;	
		}else{
			telNo.getLayoutParams().height=sdMaxHeight;
			showline.setVisibility(8);
			phoneno.setText(phoneno_c.getText());
			phoneno.setSelection(phoneno_c.getSelectionStart());
			adapter.setShowInput(phoneno);
			this.showInput = phoneno;		
		}
		telNo.invalidate();
	}
	// 写入号码
	private OnClickListener bhlistener = new OnClickListener(){
		public void onClick(View v) {
			//final EditText phoneno = (EditText) findViewById(R.id.phoneno);	
			insertText(showInput, v.getTag().toString());
			findRqeuest(showInput.getText().toString());
		}
	};
	
	/**获取EditText光标所在的位置*/
    private int getEditTextCursorIndex(EditText phoneno){
      return phoneno.getSelectionStart();
    }
    /**向EditText指定光标位置插入字符串*/
    private void insertText(EditText phoneno, String mText){
    	phoneno.getText().insert(getEditTextCursorIndex(phoneno), mText); 
        
    }
    /**向EditText指定光标位置删除字符串*/
    private void deleteText(EditText phoneno){
      //if(phoneno.getText().length()>0){
      if(getEditTextCursorIndex(phoneno)>0){
    	  phoneno.getText().delete(getEditTextCursorIndex(phoneno)-1, getEditTextCursorIndex(phoneno));
      }
      findRqeuest(phoneno.getText().toString());
    }
    public void updateText(String no){
    	this.showInput.setText(no);
    }
    
    private long mExitTime;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
    		if ((System.currentTimeMillis() - mExitTime) > 2000) {
    			//Object mHelperUtils;
    			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
    			mExitTime = System.currentTimeMillis();
    		} else {
    			finish();
    		}
    		return true;
    	}
    	return super.onKeyDown(keyCode, event);
    }
}